import { defineStore } from 'pinia';
import { reactive } from 'vue';
import { 
    getUserStats, 
    logoutUser, 
    loginUser, 
    codeLoginUser, 
    getProfileData,
    updateUsername,
    updateAvatarApi,
    changePassword,
    changePasswordByEmail,
    sendVerificationCode,
    getDefaultAvatars,
    getFollowers,
    getFollowing,
    getMutualFollowers,
    registerUser
} from '@/api/user';
import {
  doesObjectExist,
  uploadObject
} from '@/api/file'
import { getToken, setToken, removeToken, setCodeId, getCodeId } from '@/utils/auth';

import maleimage from '@/assets/image/male.jpg';
import femaleimage from '@/assets/image/female.jpg';
import { fileMd5 } from '@/utils/md5';

export const useUserStore = defineStore('user', {
  state: () => {
    // 确保初始状态完整
    const defaultStats = {
      email: '',
      avatar: null,
      name: 'guest',
      solvedCount: 0,
      totalProblems: 0,
      solvedProblems: [],
      isLoggedIn: false,
      version: '',
      codeId: '', // 新增验证码ID字段
      // 总计统计数据
      stats: {
        problems: {
          solved: 0,
          attempting: 0
        },
        blogs: {
          published: 0,
          drafts: 0
        },
        friends: {
          following: 0,
          followers: 0,
          mutual: 0
        }
      }
    };
    return {
      userStats: reactive({ ...defaultStats }),
      defaultAvatars: [], // 缓存默认头像
      avatarsLoaded: false // 标记是否已加载
    };
  },
  getters: {
    isLoggedIn: (state) => state.userStats.isLoggedIn,
    getEmail : (state) => state.userStats.email
  },

  actions: {
    // 注册用户
    async registerUser({email,username,password,avatar,code}) {
      try {
        const result = await registerUser({
            email,
            username,
            password,
            avatar,
            code,
            code_id: getCodeId()
        }
        );
        return result;
      } catch (error) {
        return {success: false, message: error};
      }
    },
    
    async login({email, password}) {
      try {
        console.log("store: call loginUser function");
        const {success,message,token,stats,version}= await loginUser(email, password);
        if (success) {
          this.userStats = reactive({
            email: stats.email,
            avatar: stats.avatar,
            name: stats.name,
            solvedCount: stats.solvedCount,
            totalProblems: stats.totalProblems,
            solvedProblems: stats.solvedProblems,
            isLoggedIn: true,
            version: version
          });
          setToken(token);
          await this.fetchUserStats(this.userStats.email,this.userStats.version); // 立即获取最新状态
          return {success};
        }
        return {success: false, message: message};
      } catch (error) {
        return {success: false, message: error};
      }
    },

    async codeLogin(email, code) {
      try {
        console.log('this.userStats.codeId:',getCodeId());
        const {success,message,token,stats,version} = await codeLoginUser(email, code, getCodeId());
        if (success) {
          this.userStats = reactive({
            email: email,
            avatar: stats.avatar,
            name: stats.name,
            solvedCount: stats.solvedCount,
            totalProblems: stats.totalProblems,
            solvedProblems: stats.solvedProblems,
            isLoggedIn: true,
            version: version
          });
          setToken(token);
          return {success: true};
        }
        return {success: false, message: message};
      } catch (error) {
        return {success: false, message:  error};
      }
    },

    async getProfile(email) {
        return await getProfileData(email);
    },

    async fetchUserStats(email = this.userStats.email, ver = this.userStats.version) {
      try {
        const {stats,version} = await getUserStats(email,ver);
        const { prodata } = await getProfileData(stats.email || this.userStats.email);
        const update = version !== this.version;
        if (this.userStats.email === "" || (stats.email ===  this.userStats.email && update)) {
            this.userStats = reactive({
            email: stats.email,
            avatar: stats.avatar,
            name: stats.name,
            solvedCount: stats.solvedCount,
            totalProblems: stats.totalProblems,
            solvedProblems: stats.solvedProblems,
            isLoggedIn: true,
            version: version,
            stats: {
                problems: {
                  solved: prodata.solved,
                  attempting: prodata.attempting
                },
                blogs: {
                  published: prodata.published,
                  drafts: prodata.drafts
                },
                friends: {
                  following: prodata.following,
                  followers: prodata.followers,
                  mutual: prodata.mutual
                }
            }
            });
        }
        return {
          stats: stats,
          prodata: prodata
        };
      } catch (error) {
        console.error('获取用户数据失败:', error);
        if (getToken() !== "")
            removeToken();
        return this.userStats;
      }
    },

    async fetchDefaultAvatars() {
      if (this.avatarsLoaded) return this.defaultAvatars;
      console.log("fetchDefaultAvatars",this.defaultAvatars);
      try {
        const list = await getDefaultAvatars();
        this.defaultAvatars.push(...list);
        this.avatarsLoaded = true;
        return this.defaultAvatars;
      } catch (error) {
        console.error('预加载头像失败:', error);
        return reactive([maleimage, femaleimage]);
      }
    },
    processAvatar(avatarData) {
      if (!avatarData) return '';
      if (typeof avatarData === 'string') {
        if (avatarData.startsWith('data:') || avatarData.includes('@/assets/')) {
          return avatarData;
        }
        return '';
      }
      return '';
    },

    isProblemSolved(problemId) {
      return this.userStats.solvedProblems?.includes(problemId) || false;
    },
    async logout() {
      try {
        const { success } = await logoutUser();
        removeToken();
        this.userStats = reactive({
          email: '',
          avatar: '',
          name: '',
          version: '',
          solvedCount: 0,
          totalProblems: 0,
          solvedProblems: [],
          isLoggedIn: false
        });
        return success;
      } catch (error) {
        console.error('登出失败:', error);
        return false;
      }
    },

    async updateUsername(newUsername) {
      try {
        const { success, message } = await updateUsername(newUsername);
        if (success) {
          this.userStats.name = newUsername;
          return { success: true };
        }
        return { success: false, message };
      } catch (error) {
        console.error('更新用户名失败:', error);
        return { success: false, message:  message };
      }
    },

    async updateAvatar(avatarData) {
      try {
        console.log(avatarData);
        const fileid = await fileMd5(new Uint8Array(avatarData));
        // 判断这个文件在对象存储中是否存在
        let { exist,path } = await doesObjectExist(fileid);
        if (!exist) {
          // 不存在，上传
          path = await uploadObject(fileid, avatarData);
        }
        const { success, message, avatar } = await updateAvatarApi(path);
        if (success) {
          this.userStats.avatar = avatar;
          return { path ,success: true };
        }
        throw message
      } catch (error) {
        console.error('更新头像失败:', error);
        throw error
      }
    },

    async changePassword(currentPassword, newPassword) {
      try {
        const { success, message } = await changePassword(currentPassword, newPassword);
        return { success, message };
      } catch (error) {
        console.error('修改密码失败:', error);
        throw error
      }
    },

    async changePasswordByEmail(verificationCode, newPassword) {
      try {
        const { success, message } = await changePasswordByEmail(verificationCode, newPassword, getCodeId());
        return { success, message };
      } catch (error) {
        console.error('通过邮箱修改密码失败:', error);
        return { success: false, message:  message };
      }
    },

    async sendVerificationCode(email) {
      try {
        const { success, code_id } = await sendVerificationCode(email);
        // if (success) {
        //   this.userStats.codeId = code_id;
        // }
        setCodeId(code_id);
        return success ;
      } catch (error) {
        console.error('发送验证码失败:', error);
        throw error
      }
    },

    async fetchFollowers(email, page = 1, pageSize = 10) {
      try {
        const { users, total } = await getFollowers(email, page, pageSize);
        return { success: true, users, total };
      } catch (error) {
        console.error('获取关注者列表失败:', error);
        return { success: false, message:  message || error, users: [], total: 0 };
      }
    },

    async fetchFollowing(email, page = 1, pageSize = 10) {
      try {
        const { users, total } = await getFollowing(email, page, pageSize);
        return { success: true, users, total };
      } catch (error) {
        console.error('获取关注列表失败:', error);
        return { success: false, message:  message || error, users: [], total: 0 };
      }
    },

    async fetchMutualFollowers(page = 1, pageSize = 10) {
      try {
        const { users, total } = await getMutualFollowers(page, pageSize);
        return { success: true, users, total };
      } catch (error) {
        console.error('获取互相关注列表失败:', error);
        return { success: false, message:  message || error, users: [], total: 0 };
      }
    }
  }
});
